;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Report.ThreeDayPlan", [])
        .controller("ThreeDayPlanCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$filter", "$timeout", "UserContextService", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $filter, $timeout, UserContextService) {
            // 三日计划列表分页信息
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };

            // 新增页的分页信息
            $scope.addPageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };

            $scope.submitted = false;

            // 标签页信息
            $scope.activeFlag = [true, false, false, false];

            $scope.markInfo = {
                allChecked: false,
                allBillChecked: false
            };

            $scope.isBooleanList = [
                { id: 0, name: "否" },
                { id: 1, name: "是" }
            ];

            // 订单类型下拉列表
            $scope.billTypeList = [
                {
                    code: "XGFT",
                    name: "发货通知单"
                },
                {
                    code: "XGSC",
                    name: "三包出库单"
                },
            ];

            $scope.listTbConfig = {
                fixedWidth: 160,
                scrollWidth: 710,
                tableCol: [
                    {
                        name: "代理商",
                        dataField: "agentName",
                        width: 150,
                        isShow: true
                    },
                    {
                        name: "单据类型",
                        dataField: "orderTypeStr",
                        width: 100,
                        isShow: true
                    },
                    {
                        name: "是否创建发运交货单",
                        dataField: "isDlvStr",
                        width: 150,
                        isShow: true
                    },
                    {
                        name: "计划日期",
                        dataField: "planDateStr",
                        width: 150,
                        isShow: true
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 120,
                        isShow: true,
                        isFixed: true
                    }
                ]
            };

            //新增时左侧列表配置项
            $scope.addLeftTbConfig = {
                scrollWidth: 630,
                fixedWidth: 40,
                tableCol: [
                    {
                        name: "业务单号",
                        dataField: "deliveryNo",
                        width: 160,
                        isShow: true,
                    },
                    {
                        name: "客户名称",
                        dataField: "purchaseOrgName",
                        width: 120,
                        isShow: true,
                    },
                    {
                        name: "采购级别",
                        dataField: "purchaseLevel",
                        width: 100,
                        isShow: true,
                    },
                    {
                        name: "创建时间",
                        dataField: "createDateStr",
                        width: 150,
                        isShow: true,
                    },
                    {
                        name: "创建者",
                        dataField: "createName",
                        width: 100,
                        isShow: true,
                    },
                ]
            };

            // 列表搜索条件
            $scope.condition = {};

            // 新增搜索条件
            $scope.addCondition = {};

            // 三日计划列表
            $scope.dataList = [];

            // 已选单据列表
            $scope.selectedList = [];

            // 新增页面单据列表
            $scope.orderDataList = [];

            $scope.detailInfo = {};

            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false
            };

            $scope.datePickerFlag = [false, false, false, false];

            $scope.tabFlag = {};

            var tabFlag = {
                0: "新增",
                1: "编辑"
            };

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.listTbConfig.fixedWidth + "px"}
                };
            };

            $scope.reset = function (obj) {
                $scope[obj] = {};
            };

            $scope.selectAll = function (dataList, allCheckKey) {
                for (var i = 0; i < dataList.length; i++) {
                    dataList[i].isChecked = $scope.markInfo[allCheckKey];
                }
            };

            $scope.selectSingle = function (item, dataList, allCheckKey) {
                var selectAll = false;
                if (!item.isChecked) {
                    selectAll = false;
                } else {
                    selectAll = checkAll(dataList);
                }
                $scope.markInfo[allCheckKey] = selectAll;
            };

            // 选择单条数据
            $scope.selectSingleOrder = function (item) {
                if (item.isChecked) {
                    $scope.selectedList.push(item);
                    $scope.selectSingle(item, $scope.orderDataList, 'allBillChecked');
                    return;
                }
                for (var i = $scope.selectedList.length - 1; i >= 0; i--) {
                    if ($scope.selectedList[i].deliveryNo === item.deliveryNo) {
                        $scope.selectedList.splice(i, 1);
                        break;
                    }
                }
                $scope.selectSingle(item, $scope.orderDataList, 'allBillChecked');
            };

            // 全选所有单据
            $scope.selectAllOrder = function () {
                var isChecked = $scope.markInfo.allBillChecked;
                angular.forEach($scope.orderDataList, function (item) {
                    // 如果全选状态为选中并且行数据为未选中，就把该条数据放入已选列表中
                    if (isChecked && !item.isChecked) {
                        item.isChecked = true;
                        $scope.selectedList.push(item);
                    }
                    // 如果全选状态为取消并且行数据为选中状态，就把该行数据从已选列表中删除
                    if (!isChecked && item.isChecked) {
                        item.isChecked = false;
                        for (var i = $scope.selectedList.length - 1; i >= 0; i--) {
                            if (item.id === $scope.selectedList[i].id) {
                                $scope.selectedList.splice(i, 1);
                            }
                        }
                    }
                })
            };

            function checkAll(dataList) {
                var selectAll = false;
                for (var i = 0, len = dataList.length; i < len; i++) {
                    if (!dataList[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false, false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            // 按钮权限code
            var btnPermissionCode = {
                threeDayPlanAdd: window.ActionCode.threeDayPlanAdd,
                threeDayPlanEdit: window.ActionCode.threeDayPlanEdit,
                threeDayPlanDelete: window.ActionCode.threeDayPlanDelete,
            };

            // 按钮权限
            $scope.btnPermission = {
                threeDayPlanAdd: true,
                threeDayPlanEdit: true,
                threeDayPlanDelete: true,
            };

            // 设置按钮权限
            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.changeTab = function (index) {
                initData();
                angular.forEach($scope.activeFlag, function (item) {
                    item = false;
                });
                $scope.activeFlag[index] = true;
            };

            // 初始化数据
            function initData () {
                $scope.markInfo = {
                    allChecked: false,
                    allBillChecked: false
                };
                $scope.submitted = false;
                $scope.detailInfo = {};
                $scope.selectedList = [];
                $scope.orderDataList = [];
                $scope.addPageInfo = {
                    totalPages: 1,
                    totalRows: 0,
                    pageSize: 10,
                    curPage: 1
                };
            }

            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "dealer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.detailInfo.clientName = data.companyName;
                    $scope.detailInfo.agentOrgId = data.dealerOrgId;
                    $scope.detailInfo.agentId = data.dealerOrgId;
                    $scope.detailInfo.agentName = data.companyName;
                })
            };

            // 批量删除三日计划
            $scope.batchDeletePlan = function () {
                var ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) ids.push(item.id);
                });
                if (ids.length === 0) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    deleteThreeDayPlan(ids);
                });
            };

            // 单个删除三日计划
            $scope.deleteSinglePlan = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    deleteThreeDayPlan([id]);
                });
            };

            function deleteThreeDayPlan (ids) {
                var url = '/threeDayPlan/remove';
                ybHttp.Post('device', url, ids).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList(1);
                })
            }

            // 进入新增页面
            $scope.goAdd = function () {
                $scope.tabFlag = {
                    type: 0,
                    name: tabFlag[0]
                };
                $scope.changeTab(1);
                var now = new Date();
                $scope.detailInfo.planDate = now;
            };

            $scope.goEdit = function (item) {
                $scope.tabFlag = {
                    type: 1,
                    name: tabFlag[1]
                };
                getDetail(item.id).then(function(value) {
                    if (!value) return;
                    item.planDate = new Date(item.planDate);
                    item.clientName = item.agentName;
                    item.agentOrgId = item.agentId;
                    $scope.detailInfo = item;
                    $scope.selectedList = value;
                    getBillDataList(1);
                });
                $scope.changeTab(1);
            };

            // 删除已选单据
            $scope.delSelected = function (deliveryNo, index) {
                for (var i = 0; i < $scope.orderDataList.length; i++) {
                    if ($scope.orderDataList[i].deliveryNo === deliveryNo) {
                        $scope.orderDataList[i].isChecked = false;
                        break;
                    }
                }
                $scope.selectedList.splice(index, 1);
            };

            // 新增三日计划
            $scope.saveData = function (valid) {
                if (!valid) {
                    $scope.submitted = true;
                    return;
                }
                if ($scope.selectedList.length === 0) {
                    ybWidget.ShowMessage('单据不能为空，请选择！', MESG_TYPE.Warn);
                    return;
                }
                var url = '/threeDayPlan/add';
                if ($scope.tabFlag.type === 1) {
                    url = '/threeDayPlan/update';
                }
                var params = angular.copy($scope.detailInfo);
                params.threeDayPlan = 1;
                params.detailVOList = angular.copy($scope.selectedList);
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    getDataList(1);
                    $scope.changeTab(0);
                })
            };

            // 搜索三日计划列表
            $scope.searchDataList = function (curPage) {
                getDataList(curPage);
            };

            // 搜索单据
            $scope.searchBill = function (curPage) {
                if (!$scope.detailInfo.orderType || !$scope.detailInfo.clientName) {
                    $scope.submitted = true;
                    return;
                }
                getBillDataList(curPage);
            };

            // 获取三日计划列表
            function getDataList (curPage) {
                var url = '/threeDayPlan/list';
                if (curPage) $scope.pageInfo.curPage = curPage;
                removeNullKey($scope.condition);
                var params = {
                    filters: angular.copy($scope.condition),
                    pageSize: $scope.pageInfo.pageSize,
                    pageNum: $scope.pageInfo.curPage
                };
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(res.value.list, function (item) {
                        item.isChecked = false;
                        item.planDateStr = $filter("YbDate")(item.planDate, "yyyy-MM-dd HH:mm:ss");
                        item.isDlvStr = $filter("TrueOrFalse")(item.isDlv, "normal");
                        item.orderTypeStr = $filter("orderType")(item.orderType);
                    });
                    $scope.pageInfo.totalRows = res.value.total;
                    $scope.pageInfo.totalPages = res.value.pages;
                    $scope.dataList = res.value.list;
                })
            }

            // 获取单据列表
            function getBillDataList (curPage) {
                var url = '/threeDayPlan/getAddList';
                if (curPage) $scope.addPageInfo.curPage = curPage;
                var filters = {
                    keyWords: $scope.detailInfo.keyWords,
                    orderType: $scope.detailInfo.orderType,
                    agentOrgId: $scope.detailInfo.agentOrgId
                };
                removeNullKey(filters);
                var params = {
                    filters: filters,
                    pageSize: $scope.addPageInfo.pageSize,
                    pageNum: $scope.addPageInfo.curPage
                };
                ybHttp.Post('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return;
                    }
                    var selectedIds = [];
                    angular.forEach($scope.selectedList, function (selected) {
                        selectedIds.push(selected.deliveryNo);
                    });
                    angular.forEach(res.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateStr = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                        if (selectedIds.indexOf(item.deliveryNo) >= 0) item.isChecked = true;
                    });
                    $scope.addPageInfo.totalRows = res.value.total;
                    $scope.addPageInfo.totalPages = res.value.pages;
                    $scope.orderDataList = res.value.list;
                })
            }

            // 进入详情页
            $scope.viewDetail = function (item) {
                getDetail(item.id).then(function (value) {
                    $scope.changeTab(2);
                    $scope.detailInfo = item;
                    $scope.detailInfo.createDateStr = $filter("YbDate")(item.createDate, "yyyy-MM-dd HH:mm:ss");
                    if (value && value.length > 0) {
                        angular.forEach(value, function (obj) {
                            obj.createDateStr = $filter("YbDate")(obj.createDate, "yyyy-MM-dd HH:mm:ss");
                        });
                        $scope.detailInfo.detailVOList = value;
                    }
                })
            };

            // 获取三日计划详情
            function getDetail (id) {
                var url = '/threeDayPlan/detail';
                return ybHttp.Get('device', url, { id: id }).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(res, MESG_TYPE.Error);
                        return false;
                    }
                    return res.value;
                })
            }

            // 删除对象中空的值
            function removeNullKey (obj) {
                Object.keys(obj).forEach(function (key) {
                    if (!obj[key] && obj[key] !== 0) delete obj[key];
                });
            }

            (function () {
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
                getDataList();
            })()
        }])
    ;
})(window, window.angular);